package com.neusoft.neuiotms.dcam.workflow.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import javax.persistence.EntityNotFoundException;
import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.neusoft.bizcore.activiti.dto.ProcessInstanceDTO;
import com.neusoft.bizcore.activiti.service.ProcessInstanceService;
import com.neusoft.bizcore.activiti.service.WorkOrderService;
import com.neusoft.bizcore.auth.common.bean.UserBean;
import com.neusoft.bizcore.web.constant.ExceptionConstants;
import com.neusoft.bizcore.web.exception.UnitedException;
import com.neusoft.neuiotms.dcam.constant.DCAMConsts;
import com.neusoft.neuiotms.dcam.fixed.dto.AssetLifeCycleDTO;
import com.neusoft.neuiotms.dcam.fixed.model.Asset;
import com.neusoft.neuiotms.dcam.fixed.repository.AssetRepository;
import com.neusoft.neuiotms.dcam.fixed.service.AssetLifeCycleService;
import com.neusoft.neuiotms.dcam.fixed.service.AssetService;
import com.neusoft.neuiotms.dcam.workflow.converter.BaofeiSLConverter;
import com.neusoft.neuiotms.dcam.workflow.dto.BaofeiSLDTO;
import com.neusoft.neuiotms.dcam.workflow.dto.ConfirmSLDTO;
import com.neusoft.neuiotms.dcam.workflow.model.BaofeiItemSL;
import com.neusoft.neuiotms.dcam.workflow.model.BaofeiSL;
import com.neusoft.neuiotms.dcam.workflow.repository.BaofeiItemSLRepository;
import com.neusoft.neuiotms.dcam.workflow.repository.BaofeiSLRepository;
import com.neusoft.neuiotms.dcam.workflow.service.BaofeiSLService;
import com.neusoft.neuiotms.dcam.workflow.service.ConfirmSLService;

import io.micrometer.core.instrument.util.StringUtils;

@Service
public class BaofeiSLServiceImpl implements BaofeiSLService {

    @Autowired
    private WorkOrderService workOrderService;
    @Autowired
    private ProcessInstanceService processInstanceService;
    @Autowired
    private BaofeiSLRepository baofeiSLRepository;
    @Autowired
    private BaofeiSLConverter baofeiSLConverter;
    @Autowired
    private BaofeiItemSLRepository baofeiItemSLRepository;
    @Autowired
    private AssetRepository assetRepository;
    @Autowired
    private AssetService assetService;
    @Autowired
    private AssetLifeCycleService assetLifeCycleService;
    @Autowired
    private ConfirmSLService confirmSLService;

    @Override
    @Transactional
    public BaofeiSLDTO create(final BaofeiSLDTO dto, final UserBean user) {

        final String taskId = dto.getTaskId();
        final ProcessInstanceDTO instance =
                this.workOrderService.submit(dto.getTitle(), DCAMConsts.PROCESSS_BAOFEI_SL_KEY, dto.getWorkOrderNum(),
                        user);
        dto.setTaskId(instance.getTaskId());
        dto.setWorkOrderNum(instance.getWorkorderNum());
        dto.setCreateUser(user.getUsername());
        dto.setCreateUserName(user.getName());

        // 查询当前workOrderNum和TaskId下是否存在记录
        final BaofeiSL oldModel = this.baofeiSLRepository.findByWorkOrderNumAndTaskId(
                dto.getWorkOrderNum(), taskId);
        if (oldModel == null) {
            dto.setId(null);
        }

        // 解锁以前的资产信息
        final List<BaofeiItemSL> all = this.baofeiItemSLRepository.findByMain_WorkOrderNum(dto.getWorkOrderNum());
        if (null != all) {
            this.assetService.updateLocked(all.stream().map(l -> l.getCode()).distinct().collect(Collectors.toList()),
                    false);
        }

        BaofeiSL model = this.baofeiSLConverter.toModel(dto);
        model = this.baofeiSLRepository.save(model);

        // 枷锁资产信息
        this.assetService.updateLocked(
                model.getDetails().stream().map(l -> l.getCode()).distinct().collect(Collectors.toList()),
                true);

        //更新资产状态为待报废
        final List<Asset> assets = model.getDetails().stream().map(s -> {
            final Asset l = this.assetRepository.findByCode(s.getCode());
            l.setLocked(false);
            l.setMoney(s.getSalvageValue());
            l.setStatus(DCAMConsts.ASSET_STATUS_TOSCRAP);
            return l;
        }).collect(Collectors.toList());

        if (assets.size() > 0) {
            this.assetRepository.saveAll(assets);
        }

        // 完成当前节点
        this.processInstanceService.complete(dto.getWorkOrderNum(), dto.getTaskId(), user);
        return this.baofeiSLConverter.toDTO(model);
    }

    @Override
    public BaofeiSLDTO detail(final String workOrderNum, final String taskId, final UserBean user) {
        BaofeiSL model = null;
        try {
            if (StringUtils.isNotBlank(workOrderNum) && !"NULL".equals(taskId)) {
                model = this.baofeiSLRepository.findByWorkOrderNumAndTaskId(workOrderNum, taskId);
                if (model == null) {
                    // 获取前一节点的TaskID
                    final String lastTaskId = this.processInstanceService.getLastTaskId(taskId, user);
                    if (lastTaskId == null) {
                        return new BaofeiSLDTO();
                    } else {
                        model = this.baofeiSLRepository.findByWorkOrderNumAndTaskId(workOrderNum,
                                lastTaskId);
                    }
                }
            } else if ("NULL".equals(taskId)) {
                model = this.baofeiSLRepository.findTopByWorkOrderNumOrderByCreateTimeDesc(workOrderNum);
            }
        } catch (final EntityNotFoundException e) {
            throw new UnitedException(ExceptionConstants.ENTITY_NOT_FOUND,
                    new Object[] {workOrderNum },
                    new Object[] {taskId });
        }
        return this.baofeiSLConverter.toDTO(model);
    }

    @Transactional
    @Override
    public void confirmCreate(final BaofeiSLDTO dto, final UserBean user) {

        this.processInstanceService.complete(dto.getWorkOrderNum(), dto.getTaskId(), user);
        // 更新资产状态为已处置
        final BaofeiSL model =
                this.baofeiSLRepository.findTopByWorkOrderNumOrderByCreateTimeDesc(dto.getWorkOrderNum());

        model.getDetails().forEach(l -> {
            dto.getDetails().forEach(s -> {
                if (l.getCode().equals(s.getCode())) {
                    l.setSalvageValue(s.getSalvageValue());
                }
            });
        });
        this.baofeiItemSLRepository.saveAll(model.getDetails());

        this.confirmSLService.create(ConfirmSLDTO.builder().workOrderNum(dto.getWorkOrderNum()).taskId(dto.getTaskId())
                .createUser(user.getUsername()).createUserName(user.getName()).mainId(model.getId()).build());

        // this.baofeiSLCompleteUpdate(model.getDetails(), dto.getWorkOrderNum());

    }

    @Override
    public void baofeiSLCompleteUpdate(final String workOrderNum) {
        final BaofeiSL model =
                this.baofeiSLRepository.findTopByWorkOrderNumOrderByCreateTimeDesc(workOrderNum);
        final List<BaofeiItemSL> details = model.getDetails();
        final List<AssetLifeCycleDTO> lifeList = new ArrayList<>();

        if ((details != null) && (details.size() > 0)) {

            final List<Asset> assets = details.stream().map(s -> {
                final Asset l = this.assetRepository.findByCode(s.getCode());
                l.setLocked(false);
                l.setManagementOrgName(null);
                l.setManagementOrgCode(null);
                l.setManagementUserCode(null);
                l.setManagementUserName(null);
                l.setMoney(s.getSalvageValue());
                l.setStatus(DCAMConsts.ASSET_STATUS_SCRAP);

                // 生命周期
                lifeList.add(AssetLifeCycleDTO.builder().code(l.getCode())
                        .lifeCycle(DCAMConsts.ASSET_LIFE_TYPE_BAOFEI)
                        .content(l.getName() + "已报废").workNum(workOrderNum).build());

                return l;
            }).collect(Collectors.toList());

            if (assets.size() > 0) {
                this.assetRepository.saveAll(assets);
            }

            if (lifeList.size() > 0) {
                this.assetLifeCycleService.batchCreate(lifeList);
            }
        }

    }

    @Override
    public BaofeiSLDTO confirmDetails(final String workOrderNum, final String taskId, final UserBean user) {

        BaofeiSL model = null;
        Long mainId = null;
        try {
            if (StringUtils.isNotBlank(workOrderNum) && !"NULL".equals(taskId)) {

                mainId = this.confirmSLService.getMainId(workOrderNum, taskId);
                if (mainId == null) {
                    // 获取前一节点的TaskID
                    final String lastTaskId = this.processInstanceService.getLastTaskId(taskId, user);
                    if (lastTaskId == null) {
                        model =
                                this.baofeiSLRepository.findTopByWorkOrderNumOrderByCreateTimeDesc(workOrderNum);
                    } else {
                        mainId = this.confirmSLService.getMainId(workOrderNum, lastTaskId);
                        model = this.baofeiSLRepository.getOne(mainId);
                    }
                } else {
                    model = this.baofeiSLRepository.getOne(mainId);
                }
            } else if ("NULL".equals(taskId)) {
                model = this.baofeiSLRepository.findTopByWorkOrderNumOrderByCreateTimeDesc(workOrderNum);
            }
        } catch (final EntityNotFoundException e) {
            throw new UnitedException(ExceptionConstants.ENTITY_NOT_FOUND,
                    new Object[] {workOrderNum },
                    new Object[] {taskId });
        }
        return this.baofeiSLConverter.toDTO(model);

    }

}
